/**
 * @module wLayoutMenu 一键排版的按钮
 * @author cy
 * @date 2021/03/29
 * @description 自定义一个一键排版的功能
 */
// 引入 wangEditor
import E from "wangeditor-zzb";
const { $, BtnMenu } = E;

// 设置默认样式
const initPStyle = "text-indent: 2em; margin: 0; font-size: 1em; font-weight: normal; color: #000";
export default class wLayoutMenu extends BtnMenu {
  constructor(editor) {
    // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
    const $elem = $(`<div class="w-e-menu" data-title="一键排版"><i class="el-icon-s-help"></i></div>`);
    super($elem, editor);
  }

  // clickHandler() {
  //   // 获取富文本编辑区的DOM
  //   let a = this.editor.txt.html()
  //   console.log('a: ', a);

  //   let childDoms = this.editor.$textElem.elems[0].childNodes;
  //   console.log('childDoms: ', childDoms);
  //   if (childDoms.length > 0) {
  //     childDoms.forEach(item => {
  //       // 富文本编辑的内容默认外层都是由p标签包容，所以直接在p标签上进行设置默认排版的样式
  //       if (item.nodeName == 'P') {
  //         item.style.cssText = initPStyle;
  //       }
  //       if (item.childNodes.length > 0) {
  //         // 遍历找到子元素中存在img标签的内容进行设置默认样式
  //         item.childNodes.forEach(child => {
  //           if (child.localName == 'img') {
  //             // 获取原图width、height
  //             let width = child.width;
  //             let height = child.height;
  //             let ratio = width / height;
  //             let setW = 600;
  //             let setH = 0;  // 等比计算
  //             if (setW / setH != ratio) {
  //               setH = setW / ratio;
  //             }
  //             // 给img标签设置行内样式
  //             child.setAttribute('width', setW);
  //             child.setAttribute('height', setH);
  //             child.style.cssText = "text-align: center";
  //           }
  //         })
  //       }
  //     })
  //   }
  // }

  clickHandler() {
    let editorhtml = this.editor.txt.html()
    console.log('editorhtml: ', editorhtml);

    var tempimg = new Array();
    var temptable = new Array();
    var tempobject = new Array();
    var tmpDiv = document.createElement("DIV");
    editorhtml = editorhtml.replace(/<div style="page-break-after: always;?">\s*<span style="display: none;?">&nbsp;<\/span>\s*<\/div>/gi, '<p>[page]</p>');
    tmpDiv.innerHTML = editorhtml.replace(/&nbsp;/gi, '').replace(/<div/gi, '<p').replace(/<\/div/gi, '</p');

    if (window.navigator.userAgent.toLowerCase().indexOf("msie") > 0) {
      tmpDiv.innerHTML = tmpDiv.innerHTML.replace(/<\/p>/gi, '<br /><\/p>')
    }
    var tables = tmpDiv.getElementsByTagName("TABLE");
    if (tables != null && tables.length > 0) {
      for (var j = 0; j < tables.length; j++) {
        temptable[temptable.length] = tables[j].outerHTML;
      }
      var formattableCount = 0;
      for (var j = 0; j < tables.length;) {
        tables[j].outerHTML = "#FormatTableID_" + formattableCount + "#";
        formattableCount++;
      }
    }

    var objects = tmpDiv.getElementsByTagName("OBJECT");
    if (objects != null && objects.length > 0) {
      for (var j = 0; j < objects.length; j++) {
        tempobject[tempobject.length] = objects[j].outerHTML;
      }
      var formatobjectCount = 0;
      for (var j = 0; j < objects.length;) {
        objects[j].outerHTML = "#FormatObjectID_" + formatobjectCount + "#";
        formatobjectCount++;
      }
    }

    var imgs = tmpDiv.getElementsByTagName("IMG");
    if (imgs != null && imgs.length > 0) {
      for (var j = 0; j < imgs.length; j++) {
        var t = document.createElement("IMG");
        t.alt = imgs[j].alt;
        t.src = imgs[j].src;
        t.width = imgs[j].width;
        t.height = imgs[j].height;
        t.align = imgs[j].align;
        tempimg[tempimg.length] = t;
      }
      var formatImgCount = 0;
      for (var j = 0; j < imgs.length;) {
        imgs[j].outerHTML = "#FormatImgID_" + formatImgCount + "#";
        formatImgCount++;
      }
    }

    var strongarray = new Array();
    var strongcount = 0;
    for (var i = 0; i < tmpDiv.getElementsByTagName('b').length; i++) {
      strongarray[strongcount] = tmpDiv.getElementsByTagName('b')[i].innerText.trim();
      tmpDiv.getElementsByTagName('b')[i].innerHTML = "#FormatStrongID_" + strongcount + "_FormatStrongID#";
      strongcount++;
    }

    for (var i = 0; i < tmpDiv.getElementsByTagName('strong').length; i++) {
      strongarray[strongcount] = tmpDiv.getElementsByTagName('strong')[i].innerText.trim();
      tmpDiv.getElementsByTagName('strong')[i].innerHTML = "#FormatStrongID_" + strongcount + "_FormatStrongID#";
      strongcount++;
    }

    var html = this.processFormatText2(tmpDiv.innerText);
    for (var i = 0; i < strongcount; i++) {
      html = html.replace("#FormatStrongID_" + i + "_FormatStrongID#", "<strong>" + strongarray[i] + "</strong>");
    }

    html = this.processFormatText(html);
    html = html.replace(/<p>\[page\]<\/p>/gi, '<div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>');
    if (temptable != null && temptable.length > 0) {
      for (var j = 0; j < temptable.length; j++) {
        var tablehtml = temptable[j];
        html = html.replace("#FormatTableID_" + j + "#", tablehtml);
      }
    }

    if (tempobject != null && tempobject.length > 0) {
      for (var j = 0; j < tempobject.length; j++) {
        var objecthtml = "<p align=\"center\">" + tempobject[j] + "</p>";
        html = html.replace("#FormatObjectID_" + j + "#", objecthtml);
      }
    }

    if (tempimg != null && tempimg.length > 0) {
      for (var j = 0; j < tempimg.length; j++) {
        var imgheight = "";
        var imgwidth = "";
        if (tempimg[j].height != 0) imaheight = " height=\"" + tempimg[j].height + "\"";
        if (tempimg[j].width != 0) imgwidth = " width=\"" + tempimg[j].width + "\"";
        var imgalign = "";
        if (tempimg[j].align != "") imgalign = " align=\"" + tempimg[j].align + "\"";
        var imghtml = "<p align=\"center\"><img src=\"" + tempimg[j].src + "\" alt=\"" + tempimg[j].alt + "\"" + imgwidth + " " + imgheight + " align=\"" + tempimg[j].align + "\" border=\"0\"></p>";
        html = html.replace("#FormatImgID_" + j + "#", imghtml);
      }
    }

    while (html.indexOf("</p></p>") != -1) html = html.replace("</p></p>", "</p>");
    while (html.indexOf('<p><p align="center">') != -1) html = html.replace('<p><p align="center">', '<p align="center">');
    // console.log('html: ', html);
    this.editor.txt.html(html)
    return html;
  }
  processFormatText(textContext) {
    var text = this.DBC2SBC(textContext);
    var prefix = "";
    var tmps = text.split("\n");
    var html = "";
    for (var i = 0; i < tmps.length; i++) {
      var tmp = tmps[i].trim();
      if (tmp.length > 0) {
        var reg = /#Format[A-Za-z]+_\d+#/gi;
        var f = reg.exec(tmp);
        if (f != null) {
          tmp = tmp.replace(/#Format[A-Za-z]+_\d+#/gi, '');
          html += f;
          if (tmp != "") {
            html += tmp;
          }

        } else {
          html += tmp;
        }
      }
    }
    return html;
  }
  DBC2SBC(str) {
    var result = '';
    for (var i = 0; i < str.length; i++) {
      var code = str.charCodeAt(i);
      // “65281”是“！”，“65373”是“｝”，“65292”是“，”。不转换"，"

      if (code >= 65281 && code < 65373 && code != 65292 && code != 65306) {
        //  “65248”是转换码距
        result += String.fromCharCode(str.charCodeAt(i) - 65248);
      } else {
        result += str.charAt(i);
      }
    }
    return result;
  }
  processFormatText2(textContext) {
    var text = this.DBC2SBC(textContext);
    var prefix = "";
    var tmps = text.split("\n");
    var html = "";
    var paraStr = "";
    for (var i = 0; i < tmps.length; i++) {
      var tmp = tmps[i].trim();
      if (tmp.length > 0) {
        paraStr = "";
        var k = tmp.indexOf("#FormatStrongID_");
        if (k == -1) {
          paraStr = tmp;
        } else {
          for (; k != -1 && k <= tmp.length;) {
            if (k == 0) {
              var kend = tmp.indexOf("_FormatStrongID#", k + 16);
              paraStr += tmp.substr(k, kend - k + 16);
              tmp = tmp.substr(kend + 16);
              k = tmp.indexOf("#FormatStrongID_");
            } else {
              paraStr += tmp.substr(0, k);
              tmp = tmp.substr(k);
              k = tmp.indexOf("#FormatStrongID_");
            }
          }
          if (tmp.length > 0) {
            paraStr += tmp;
          }
        }
        html += "<p>" + paraStr + "</p>\n";
      }
    }
    return html;
  }

  // 菜单是否被激活（如果不需要，这个函数可以空着）
  tryChangeActive() { }
}